# coding=utf-8

"""
    Created by Kalyter on 2017-11-16.
"""
import time

from learning.scientifc.config import Config
from learning.util.log_util import get_logger

logger = get_logger()


class App(object):
    """对外开放的做科学计算处理的客户端"""

    def __init__(self, config=None):
        self.config = config if config else Config()
        self.__jobs = []

    def load_jobs(self):
        """从配置加载所有作业"""

        logger.info('开始加载所有作业')
        jobs = self.config.get('JOBS', [])
        for job in jobs:
            cls_name = job.get('cls')
            args = job.get('args', ())
            kwargs = job.get('kwargs', {})

            logger.info('开始加载 %s', cls_name)
            module_path, module_class_name = cls_name.rsplit('.', 1)
            modules = __import__(module_path, fromlist=[module_class_name])
            cls = getattr(modules, module_class_name)
            if 'from_app' in dir(cls):
                from_app = getattr(cls, 'from_app')
                job = from_app(self)
            else:
                job = cls()
            self.__jobs.append({
                'job': job,
                'args': args,
                'kwargs': kwargs
            })
            logger.info('加载成功 %s', cls_name)
        logger.info('所有作业加载完毕')

    def add_job(self, job_cls, *args, **kwargs):
        job_dir = dir(job_cls)
        if 'from_app' in job_dir:
            from_app = getattr(job_cls, 'from_app')
            job = from_app(self)
        else:
            job = job_cls()
        self.__jobs.append({
            'job': job,
            'args': args,
            'kwargs': kwargs
        })

    def run(self):
        """作业运行接口"""
        for i, job_config in enumerate(self.__jobs):
            job = job_config.get('job')
            job_args = job_config.get('args')
            job_kwargs = job_config.get('kwargs')
            start_time = time.time()
            logger.info('作业序号[%s]  作业名称[%s]  开始运行', i, job.name)
            try:
                job.run(*job_args, **job_kwargs)
                end_time = time.time()
                logger.info('作业序号[%s]  作业名称[%s]  运行完成   耗时 -> %.2fs',
                            i, job.name, (end_time - start_time))
            except Exception as e:
                logger.info('作业序号[%s]  作业名称[%s] 运行出错', i, job.name)
                logger.exception(e)
